#!/usr/bin/env node
/**
 * 简化的服务器启动脚本
 * 解决模块重复声明问题
 */

const http = require('http');
const express = require('express');
const WebSocket = require('ws');
const path = require('path');
const bcrypt = require('bcrypt');

// 导入数据库模块
const { User, Document, DocumentCollaborator, Topic } = require('./db');

// 创建Express应用
const app = express();
const PORT = 3000;

// CORS middleware
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname, '../dist')));

// API路由
const router = express.Router();

// 用户注册
router.post('/register', (req, res) => {
  const { username, password } = req.body;
  
  if (!username || !password) {
    return res.status(400).json({ error: 'Username and password are required' });
  }
  
  User.findByUsername(username, (err, user) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (user) {
      return res.status(400).json({ error: 'User already exists' });
    }
    
    bcrypt.hash(password, 10, (err, hash) => {
      if (err) {
        return res.status(500).json({ error: 'Error hashing password' });
      }
      
      User.create(username, hash, (err, userId) => {
        if (err) {
          return res.status(500).json({ error: 'Error creating user' });
        }
        
        res.status(201).json({ 
          message: 'User created successfully',
          user: { id: userId, username }
        });
      });
    });
  });
});

// 用户登录
router.post('/login', (req, res) => {
  const { username, password } = req.body;
  
  if (!username || !password) {
    return res.status(400).json({ error: 'Username and password are required' });
  }
  
  User.findByUsername(username, (err, user) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (!user) {
      bcrypt.hash(password, 10, (err, hash) => {
        if (err) {
          return res.status(500).json({ error: 'Error hashing password' });
        }
        
        User.create(username, hash, (err, userId) => {
          if (err) {
            return res.status(500).json({ error: 'Error creating user' });
          }
          
          res.json({ 
            message: 'User created and logged in successfully',
            user: { id: userId, username }
          });
        });
      });
    } else {
      bcrypt.compare(password, user.password, (err, result) => {
        if (err) {
          return res.status(500).json({ error: 'Error comparing passwords' });
        }
        
        if (result) {
          res.json({ 
            message: 'Login successful',
            user: { id: user.id, username: user.username }
          });
        } else {
          res.status(401).json({ error: 'Invalid password' });
        }
      });
    }
  });
});

// 获取用户文档树形结构
router.get('/documents/user/:userId/tree', (req, res) => {
  const userId = req.params.userId;
  
  Document.findByUserId(userId, (err, documents) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    const tree = Document.buildTree(documents);
    res.json({ tree });
  });
});

// 获取用户在特定主题下的文档树形结构
router.get('/documents/user/:userId/topic/:topicId/tree', (req, res) => {
  const userId = req.params.userId;
  const topicId = req.params.topicId;
  
  Document.findByUserIdAndTopic(userId, topicId, (err, documents) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ error: 'Database error' });
    }
    
    const tree = Document.buildTree(documents);
    res.json({ tree });
  });
});

// 创建文档或文件夹
router.post('/documents', (req, res) => {
  const { title, content, type, parent_id, owner_id, topic_id } = req.body;
  
  console.log('Creating document:', { title, type, parent_id, owner_id, topic_id });
  
  const documentType = type || 'document';
  if (!['folder', 'document'].includes(documentType)) {
    return res.status(400).json({ error: 'Type must be either "folder" or "document"' });
  }
  
  Document.create(title, content, documentType, parent_id, owner_id, topic_id, (err, documentId) => {
    if (err) {
      console.error('Document creation error:', err);
      return res.status(500).json({ error: 'Database error' });
    }
    
    console.log('Document created with ID:', documentId);
    res.status(201).json({ 
      message: 'Document created successfully',
      document: { id: documentId, title, content, type: documentType, parent_id, owner_id, topic_id }
    });
  });
});

// 获取文档详情
router.get('/documents/:id', (req, res) => {
  const id = req.params.id;
  
  Document.findById(id, (err, document) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (!document) {
      return res.status(404).json({ error: 'Document not found' });
    }
    
    res.json({ document });
  });
});

// 更新文档
router.put('/documents/:id', (req, res) => {
  const id = req.params.id;
  const { title, content } = req.body;
  
  Document.update(id, title, content, (err, changes) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (changes === 0) {
      return res.status(404).json({ error: 'Document not found' });
    }
    
    res.json({ message: 'Document updated successfully' });
  });
});

// 移动文档
router.put('/documents/:id/move', (req, res) => {
  const id = req.params.id;
  const { parent_id } = req.body;
  
  Document.move(id, parent_id, (err, changes) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (changes === 0) {
      return res.status(404).json({ error: 'Document not found' });
    }
    
    res.json({ message: 'Document moved successfully' });
  });
});

// 删除文档
router.delete('/documents/:id', (req, res) => {
  const id = req.params.id;
  
  Document.delete(id, (err, changes) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (changes === 0) {
      return res.status(404).json({ error: 'Document not found' });
    }
    
    res.json({ message: 'Document deleted successfully' });
  });
});

// ============ 主题管理 API ============

// 获取所有主题
router.get('/topics', (req, res) => {
  Topic.findAll((err, topics) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    res.json({ topics });
  });
});

// 创建主题
router.post('/topics', (req, res) => {
  const { title, description, color, icon, createdBy } = req.body;
  
  if (!title) {
    return res.status(400).json({ error: 'Topic title is required' });
  }
  
  Topic.create(title, description, color, icon, createdBy, (err, topicId) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    res.status(201).json({ 
      message: 'Topic created successfully',
      topic: { id: topicId, title, description, color, icon, createdBy }
    });
  });
});

// 设置默认主题
router.put('/topics/:id/default', (req, res) => {
  const id = req.params.id;
  
  Topic.setDefault(id, (err, changes) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    if (changes === 0) {
      return res.status(404).json({ error: 'Topic not found' });
    }
    
    res.json({ message: 'Default topic updated successfully' });
  });
});

// 删除主题
router.delete('/topics/:id', (req, res) => {
  const id = req.params.id;
  
  Topic.delete(id, (err, changes) => {
    if (err) {
      return res.status(500).json({ error: err.message || 'Database error' });
    }
    
    if (changes === 0) {
      return res.status(404).json({ error: 'Topic not found or cannot delete default topic' });
    }
    
    res.json({ message: 'Topic deleted successfully' });
  });
});

// 使用API路由
app.use('/api', router);

// 创建HTTP服务器
const server = http.createServer(app);

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });
const clients = new Map();

wss.on('connection', (ws, req) => {
  console.log('[Backend] New client connected');
  clients.set(ws, { id: null, name: null, color: null, documentId: null });
  
  ws.send(JSON.stringify({ type: 'connected', message: 'Connected to collaboration server' }));
  
  ws.on('message', (message) => {
    try {
      const data = JSON.parse(message);
      console.log('[Backend] Received message:', data);
      
      switch (data.type) {
        case 'user-join':
          clients.set(ws, data.user);
          console.log('[Backend] Updated client info:', data.user);
          console.log('[Backend] Current clients map:', Array.from(clients.values()));
          let broadcastCount = 0;
          clients.forEach((userInfo, client) => {
            console.log('[Backend] Checking client:', userInfo.id, 'documentId:', userInfo.documentId, 'vs incoming:', data.user.documentId);
            if (client !== ws && client.readyState === WebSocket.OPEN && 
                userInfo.documentId === data.user.documentId) {
              client.send(JSON.stringify({
                type: 'user-join',
                user: data.user
              }));
              broadcastCount++;
            }
          });
          console.log(`[Backend] Broadcasted user-join to ${broadcastCount} clients`);
          break;
          
        case 'document-update':
          console.log('[Backend] Processing document-update for documentId:', data.documentId);
          console.log('[Backend] Current clients with documentIds:', Array.from(clients.values()).map(u => ({ id: u.id, name: u.name, documentId: u.documentId })));
          let docUpdateBroadcastCount = 0;
          clients.forEach((userInfo, client) => {
            console.log('[Backend] Checking client for document-update:', userInfo.id, 'name:', userInfo.name, 'documentId:', userInfo.documentId, 'vs:', data.documentId, 'match:', userInfo.documentId === data.documentId, 'readyState:', client.readyState);
            if (client !== ws && client.readyState === WebSocket.OPEN && 
                userInfo.documentId === data.documentId) {
              client.send(JSON.stringify({
                type: 'document-update',
                content: data.content,
                documentId: data.documentId
              }));
              docUpdateBroadcastCount++;
              console.log('[Backend] Sent document-update to client:', userInfo.id, userInfo.name);
            } else {
              console.log('[Backend] Skipped client:', userInfo.id, 'reasons:', {
                isSender: client === ws,
                isOpen: client.readyState === WebSocket.OPEN,
                documentMatch: userInfo.documentId === data.documentId
              });
            }
          });
          console.log(`[Backend] Broadcasted document-update to ${docUpdateBroadcastCount} clients`);
          break;
          
        default:
          clients.forEach((userInfo, client) => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
              client.send(JSON.stringify(data));
            }
          });
      }
    } catch (error) {
      console.error('Error parsing message:', error);
    }
  });
  
  ws.on('close', (code, reason) => {
    console.log('Client disconnected. Code:', code, 'Reason:', reason?.toString());
    const userInfo = clients.get(ws);
    if (userInfo) {
      let leaveBroadcastCount = 0;
      clients.forEach((info, client) => {
        if (client !== ws && client.readyState === WebSocket.OPEN && 
            info.documentId === userInfo.documentId) {
          client.send(JSON.stringify({
            type: 'user-leave',
            user: userInfo
          }));
          leaveBroadcastCount++;
        }
      });
      console.log(`Broadcasted user-leave to ${leaveBroadcastCount} clients`);
    }
    clients.delete(ws);
    console.log('Client removed from clients map. Remaining clients:', clients.size);
  });
  
  ws.on('error', (error) => {
    console.error('WebSocket error:', error);
    clients.delete(ws);
  });
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log(`WebSocket server running on ws://localhost:${PORT}`);
});